// pages/source/imgSourceList/imgSourceList.js
const common = require('../../../utils/util.js')
const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        type: null,
        classfy: null,
        imgList: [],
        nowPage: 0,
        isLoading: false,
        isAll: false,
        userCode: ''
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        this.setData({
            type: options.type,
            classfy: options.classfy
        })
        this.getImgList()
        this.getUserCode()
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {
        this.getImgList()
    },

    getUserCode: function() {
        const that = this
        let data = {
            store_id: wx.getStorageSync('storeId')
        }
        common.post('QrCodes/app_create_qr', data).then(function(res) {
            that.setData({
                userCode: res
            })
        }).catch(function(e) {})
    },

    getImgList: function() {
        if (this.data.isLoading) {
            return
        }
        if (this.data.isAll) {
            return
        }
        const that = this
        let imgList = this.data.imgList
        let data = {
            category_id: this.data.classfy,
            type: this.data.type,
            limit: 10,
            page: this.data.nowPage
        }
        this.setData({
            isLoading: true
        })
        wx.showLoading({
            title: '加载中',
        })
        common.post('Fodder/fodder_list', data).then(function(res) {
            that.setData({
                isLoading: false
            })
            wx.hideLoading()
            if (res.code == 204) {
                that.setData({
                    imgList: imgList,
                    isAll: true
                })
            } else {
                imgList = imgList.concat(res)
                that.setData({
                    imgList: imgList,
                    nowPage: that.data.nowPage + 1
                })
            }
        }).catch(function(e) {})
    },

    promisify: function(api) {
        return (options, ...params) => {
            return new Promise((resolve, reject) => {
                const extras = {
                    success: resolve,
                    fail: reject
                }
                api({
                    ...options,
                    ...extras
                }, ...params)
            })
        }
    },

    circleImg: function(ctx, img, x, y, r) {
        ctx.save();
        var d = 2 * r;
        var cx = x + r;
        var cy = y + r;
        ctx.arc(cx, cy, r, 0, 2 * Math.PI);
        ctx.clip();
        ctx.drawImage(img, x, y, d, d);
        ctx.restore();
    },

    createImg: function(e) {
        wx.showLoading({
            title: '正在生成图片...',
        })
        if (e.currentTarget.dataset.classfy == 7 || e.currentTarget.dataset.classfy == 8) {
            const that = this
            const wxGetImageInfo = this.promisify(wx.getImageInfo)
            Promise.all([
                wxGetImageInfo({
                    src: 'https:' + e.currentTarget.dataset.img.split(':')[1]
                }),
                wxGetImageInfo({
                    src: 'https:' + that.data.userCode.split(':')[1]
                })
            ]).then(res => {
                const ctx = wx.createCanvasContext('shareCanvas')
                ctx.drawImage(res[0].path, 0, 0, 750, 1234)
                ctx.drawImage(res[1].path, 520, 985, 180, 180)
                ctx.draw(false, function(e) {
                    wx.hideLoading()
                    const wxCanvasToTempFilePath = that.promisify(wx.canvasToTempFilePath)
                    const wxSaveImageToPhotosAlbum = that.promisify(wx.saveImageToPhotosAlbum)
                    wxCanvasToTempFilePath({
                        canvasId: 'shareCanvas',
                        x: 0,
                        y: 0,
                        width: 750,
                        height: 1234,
                        destWidth: 750,
                        destHeight: 1234
                    }, this).then(res => {
                        return wxSaveImageToPhotosAlbum({
                            filePath: res.tempFilePath
                        })
                    }).then(res => {
                        wx.showToast({
                            title: '已保存到相册'
                        })
                    })
                })
            })
        } else {
            wx.downloadFile({
                url: 'https:' + e.currentTarget.dataset.img.split(':')[1],
                success(res) {
                    // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
                    if (res.statusCode === 200) {
                        const saveImg = res.tempFilePath
                        wx.saveImageToPhotosAlbum({
                            filePath: res.tempFilePath,
                            success: function(data) {
                                wx.hideLoading()
                                wx.showToast({
                                    title: '保存成功',
                                    icon: 'success',
                                    duration: 2000
                                })
                            },
                            fail: function(err) {
                                wx.hideLoading()
                                if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
                                    wx.showModal({
                                        title: '用户未授权',
                                        content: '请先开启保存到相册权限，开启后即可保存图片',
                                        success(res) {
                                            if (res.confirm) {
                                                wx.openSetting({
                                                    success(settingdata) {
                                                        if (settingdata.authSetting['scope.writePhotosAlbum']) {
                                                            wx.saveImageToPhotosAlbum({
                                                                filePath: saveImg,
                                                                success(res) {
                                                                    wx.showToast({
                                                                        title: '保存成功',
                                                                        icon: 'success',
                                                                        duration: 2000
                                                                    })
                                                                }
                                                            })
                                                        } else {
                                                            wx.showToast({
                                                                title: '保存图片失败，请确认开启授权后重新保存图片',
                                                                icon: 'none',
                                                                duration: 2000
                                                            })
                                                        }
                                                    }
                                                })
                                            } else if (res.cancel) {
                                                wx.showToast({
                                                    title: '保存图片失败，请确认开启授权后重新保存图片',
                                                    icon: 'none',
                                                    duration: 2000
                                                })
                                            }
                                        }
                                    })
                                }
                            }
                        })
                    }
                }
            })
        }
    }
})